package com.wsfPro.controllers.dto.system.userDetails;

import com.wsfPro.core.base.SysConstants;
import com.wsfPro.util.StringUtils;
import com.wsfPro.util.jwt.JwttokenconfigEnum;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class UserDetailsImpl extends AbstractUserDto implements UserDetails {

  private Collection<SimpleGrantedAuthority> authorities;
  private boolean accountNonExpired;
  private boolean accountNonLocked;
  private boolean credentialsNonExpired;
  private boolean enabled;

  private UserDetailsImpl() {};

  public UserDetailsImpl(
      String id,
      String username,
      String password,
      Collection<SimpleGrantedAuthority> authorities,
      boolean accountNonExpired,
      boolean accountNonLocked,
      boolean credentialsNonExpired,
      boolean enabled) {
    super.setId(id);
    super.setName(username);
    super.setPassword(password);
    this.authorities = authorities;
    this.accountNonExpired = accountNonExpired;
    this.accountNonLocked = accountNonLocked;
    this.credentialsNonExpired = credentialsNonExpired;
    this.enabled = enabled;
  }

  public static UserDetails createUserDetailByMap(Map jwtTokenMap) {
    List<Map> roleMapList = (List<Map>) jwtTokenMap.get(JwttokenconfigEnum.roles.getValue());
    HashSet<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
    for (Map roleMap : roleMapList) {
      SimpleGrantedAuthority simpleGrantedAuthority =
          new SimpleGrantedAuthority(roleMap.get("authority").toString());
      authorities.add(simpleGrantedAuthority);
    }
    //        accountNonExpired accountNonLocked credentialsNonExpired enabled
    UserDetailsImpl userDetails =
        new UserDetailsImpl(
            jwtTokenMap.get(JwttokenconfigEnum.jti.getValue()).toString(),
            StringUtils.toStringByObject(jwtTokenMap.get(JwttokenconfigEnum.sub.getValue())),
            StringUtils.toStringByObject(jwtTokenMap.get(SysConstants.PASSWORD.getValue())),
            authorities,
            true,
            true,
            true,
            true);
    return userDetails;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return authorities;
  }

  @Override
  public String getPassword() {
    return super.getPassword();
  }

  @Override
  public String getUsername() {
    return super.getName();
  }

  @Override
  public boolean isAccountNonExpired() {
    return accountNonExpired;
  }

  @Override
  public boolean isAccountNonLocked() {
    return accountNonLocked;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return credentialsNonExpired;
  }

  @Override
  public boolean isEnabled() {
    return enabled;
  }
}
